package com.starshineworks.util;

import java.util.Properties;
import java.util.Scanner;
import java.io.File;
import javax.mail.*;
import javax.mail.internet.*;

public class Emailer {

    public boolean send(String to, String from,
                        String subject, String body, 
                        String attachment) {
        try {
            final String fcred = Util.userHome + "/.emailrc";
            Scanner sc = new Scanner(new File(fcred));
            final String user = sc.next();
            final String pass = sc.next();

            final String SMTPServer = "smtp.gmail.com";
            // XXX final String 
            if (from == null) {
                from = "fieldadmin@ebusc.org";
            }

            if (to == null || from == null || subject == null || body == null) {
                return false;
            }
            if (to.length() == 0 || from.length() == 0 || subject.length() == 0 || body.length() == 0) {
                return false;
            }

            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "587");

            Session session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(user, pass);
                        }
                    });
            try {

                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                message.setSender(new InternetAddress(from));
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(to));
                message.setSubject(subject);
                message.setText(body);
                Transport.send(message);

                System.out.println("Done");

            } catch (MessagingException e) {
                Util.handleException(e);
                return false;
            }

        } catch (Exception e) {
            Util.handleException(e);
            return false;
        }

        return true;
    }
}
